package projorientado.anpr.impl;

import java.util.Iterator;
import projorientado.anpr.OCRPlate;
import projorientado.anpr.OCRPlateProvider;
import projorientado.anpr.PlateRecognizer;
import projorientado.anpr.PlateRecognizerProvider;
import projorientado.spi.ServiceProvider;
import projorientado.util.CodeTokenizer;
import projorientado.util.CodeTokenizer.CodeElement;

public class BPlateRecognizerProvider implements ServiceProvider<PlateRecognizer> {

    private static final BPlateRecognizerProvider instance = new BPlateRecognizerProvider();
    
    static {
        PlateRecognizerProvider.getInstance().registerServiceProvider("bPlateRecognizer", instance);
    }
    
    private BPlateRecognizerProvider() {
        
    }
    
    public PlateRecognizer getService(String s) {
        BPlateRecognizerProps props = new BPlateRecognizerProps();
        OCRPlate ocr = null;
        
        CodeTokenizer.CodeBlock root = CodeTokenizer.singleParse(s);
        
        Iterator<CodeTokenizer.CodeElement> it = root.childs.iterator();
        while(it.hasNext()) {
            CodeElement e = it.next();
            if(e instanceof CodeTokenizer.CodeTextBlock) {
                CodeTokenizer.CodeTextBlock tblock = (CodeTokenizer.CodeTextBlock)e;
                String name = tblock.name.toLowerCase();
                
                if(name.equals("properties") || name.equals("props")) {
                    props.loadFromString(tblock.text);
                } else if(name.startsWith("ocr:") || name.startsWith("ocrplate:")) {
                    String service = tblock.name.substring(name.indexOf(':')+1);
                    ocr = OCRPlateProvider.getOCRPlate(service, tblock.text);
                }
            }
        }
        
        BPlateRecognizer bplate = new BPlateRecognizer(ocr,props);
        
        return bplate;
    }

}
